<template>
  <el-drawer v-model="drawer" title="单词笔记管理" :with-header="true" size="80%" class="notes-drawer"
    :style="{ color: 'var(--btn-text)', background: 'var(--bg-color)' }">
    <div class="notes-container">
      <!-- 顶部操作栏 -->
      <div class="notes-header">
        <h2>{{ props.word }} 的笔记</h2>
        <el-button type="primary" @click="showAddDialog">
          <el-icon>
            <Plus />
          </el-icon> 添加新笔记
        </el-button>
      </div>

      <!-- 笔记列表 -->
      <div class="notes-list">
        <div v-for="note in notes" :key="note.id" class="note-card"
          :style="{ background: 'var(--card-bg)', borderColor: 'var(--border-color)' }">
          <div class="note-content">
            <p>{{ note.note }}</p>
          </div>
          <div class="note-meta">
            <span class="note-date">{{ formatDate(note.created_at) }}</span>
            <div class="note-actions">
              <el-button size="small" @click="editNote(note)">
                <el-icon>
                  <Edit />
                </el-icon> 编辑
              </el-button>
              <el-button size="small" type="danger" @click="confirmDeleteNote(note)">
                <el-icon>
                  <Delete />
                </el-icon> 删除
              </el-button>
            </div>
          </div>
        </div>

        <el-empty description="暂无笔记" v-if="!loading && notes.length === 0" />
      </div>
    </div>

    <!-- 添加/编辑笔记对话框 -->
    <el-dialog v-model="noteDialogVisible" :title="isEditing ? '编辑笔记' : '添加新笔记'" width="50%"
      :close-on-click-modal="false">
      <el-form :model="currentNote" label-width="80px">
        <el-form-item label="单词">
          <el-input v-model="props.word" disabled />
        </el-form-item>
        <el-form-item label="笔记内容">
          <el-input v-model="currentNote.note" type="textarea" :rows="5" placeholder="请输入笔记内容..." maxlength="500"
            show-word-limit />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="noteDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="saveNote" :loading="saving">
          {{ isEditing ? '更新' : '保存' }}
        </el-button>
      </template>
    </el-dialog>
  </el-drawer>
</template>

<script setup>
import { ref, computed, watch, reactive } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Edit, Delete } from '@element-plus/icons-vue'
// import { getUserNotes, addUserNote, updateUserNote, deleteUserNote } from "../api/authService.js";
import { getUserNotes, addNote, deleteNoteApi, editNoteApi } from "../api/authService.js";
import { el } from 'element-plus/es/locale/index.mjs';

const props = defineProps({
  word: String,
  show: Boolean,
  // 可以继续接收其他属性
  userid: String,
  wordData: Object
});
// console.log(props, 'props');

const drawer = ref(props.show)
const notes = ref([])
const loading = ref(false)
const saving = ref(false)
const noteDialogVisible = ref(false)
const userid = ref(parseInt(props.userid, 10));
const noteId = ref()
// 如果 props.wordData 是有效对象，则使用 reactive，否则处理默认值
const wordid = reactive(props.wordData || { word_id: null, word: '', definition: '', phonetic: '' });
// console.log(userid.value, 'userid');


// 当 wordData 变化时重新设置 wordid
watch(() => props.wordData, (newWordData) => {
  // console.log(newWordData, 'newWordData');
  if (newWordData) {
    wordid.word_id = newWordData.word_id;
    wordid.word = newWordData.word;
    wordid.definition = newWordData.definition;
    wordid.phonetic = newWordData.phonetic;


    // console.log(wordid.definition, 'word_id');
  }
});


// 直接访问即可
const currentNote = ref({
  id: null,
  note: '',
  word_id: wordid.word_id,
  user_id: userid.value
})

const isEditing = ref(false)

// 监听显示状态变化
watch(() => props.show, async (newVal) => {
  drawer.value = newVal
  if (newVal) {
    await loadNotes()
  }
})

// 加载笔记列表
const loadNotes = async () => {
  loading.value = true
  try {
    const response = await getUserNotes(userid.value, wordid.word_id) // 使用您的userId和wordId
    if (response.success) {
      notes.value = response.notes
    } else {
      ElMessage.error('获取笔记失败')
    }
  } catch (error) {
    ElMessage.error('获取笔记失败: ' + error.message)
  } finally {
    loading.value = false
  }
}

// 显示添加笔记对话框
const showAddDialog = () => {
  currentNote.value = {
    id: null,
    note: '',
    word_id: wordid.word_id,
    user_id: userid.value
  }
  isEditing.value = false
  noteDialogVisible.value = true
}

// // 编辑笔记
// const editNote = (note) => {
//   currentNote.value = { ...note }
//   isEditing.value = true
//   noteDialogVisible.value = true
// }

// 添加笔记
const addNoteflag = async () => {
  saving.value = true
  try {
    const response = await addNote(userid.value, wordid.word_id, currentNote.value.note) // 使用 userId, wordId 和笔记内容
    if (response.success) {
      ElMessage.success('笔记添加成功')
      // 如果需要，可以重新加载笔记列表
      loadNotes()
      noteDialogVisible.value = false
    } else {
      ElMessage.error(response.message || '添加笔记失败')
    }
  } catch (error) {
    ElMessage.error('添加笔记失败: ' + error.message)
  } finally {
    saving.value = false
  }
}



// 保存笔记
const saveNote = async () => {
  if (!currentNote.value.note.trim()) {
    ElMessage.warning('请填写笔记内容')
    return
  }
  // console.log(isEditing.value);
  if (isEditing.value === false) {
    addNoteflag()
  } else {
    editNoteflag(noteId.value)
  }


  // console.log(currentNote.value.note);

  // try {
  //   if (isEditing.value) {
  //     // 更新笔记
  //     const response = await updateUserNote(currentNote.value.id, currentNote.value)
  //     if (response.success) {
  //       ElMessage.success('笔记更新成功')
  //     }
  //   } else {
  //     // 添加新笔记
  //     const response = await addUserNote(currentNote.value)
  //     if (response.success) {
  //       ElMessage.success('笔记添加成功')
  //     }
  //   }
  //   await loadNotes()
  //   noteDialogVisible.value = false
  // } catch (error) {
  //   ElMessage.error('操作失败: ' + error.message)
  // } finally {
  //   saving.value = false
  // }
}


//删除用户note
const confirmDeleteNote = (noteId) => {
  ElMessageBox.confirm('确定要删除这条笔记吗？', '提示', {
    confirmButtonText: '删除',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    deleteNote(noteId);
  }).catch(() => {
    ElMessage.info('已取消删除');
  });
};

const deleteNote = async (noteId) => {
  // console.log(noteId,'csaaca');

  try {
    const response = await deleteNoteApi(noteId.id);
    if (response.success) {
      ElMessage.success('笔记删除成功');
      loadNotes(); // 刷新
    } else {
      ElMessage.error(response.message || '删除失败');
    }
  } catch (error) {
    ElMessage.error('删除失败: ' + error.message);
  }
};

const editNoteflag = async (noteId) => {

  try {
    const response = await editNoteApi(noteId.id, currentNote.value.note);
    if (response.success) {
      ElMessage.success('笔记更新成功');
      loadNotes(); // 重新加载笔记
      noteDialogVisible.value = false
    } else {
      ElMessage.error(response.message);
    }
  } catch (error) {
    ElMessage.error('更新失败: ' + error.message);
  }
};



// 编辑笔记
const editNote = (note) => {
  currentNote.value = { ...note }
  isEditing.value = true
  noteDialogVisible.value = true
  noteId.value = note
  // console.log(noteId.value);

}





// 确认删除笔记
const confirmDelete = (note) => {
  // ElMessageBox.confirm(
  //   `确定要删除这条笔记吗?`,
  //   '警告',
  //   {
  //     confirmButtonText: '确定',
  //     cancelButtonText: '取消',
  //     type: 'warning'
  //   }
  // ).then(async () => {
  //   try {
  //     const response = await deleteUserNote(note.id)
  //     if (response.success) {
  //       ElMessage.success('笔记删除成功')
  //       await loadNotes()
  //     }
  //   } catch (error) {
  //     ElMessage.error('删除失败: ' + error.message)
  //   }
  // }).catch(() => { })
}

// 格式化日期
const formatDate = (dateString) => {
  if (!dateString) return ''
  const date = new Date(dateString)
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  })
}
</script>

<style scoped>
.notes-drawer {
  padding: 20px;
}

.notes-container {
  padding: 0 20px;
  height: 100%;
  display: flex;
  flex-direction: column;
}

.notes-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 15px;
  border-bottom: 1px solid var(--border-color);
}

.notes-list {
  flex: 1;
  overflow-y: auto;
  padding-right: 10px;
}

.note-card {
  padding: 15px;
  margin-bottom: 15px;
  border-radius: 8px;
  border: 1px solid;
  box-shadow: 0 2px 8px var(--shadow-color);
  transition: all 0.3s ease;
}

.note-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px var(--shadow-color);
}

.note-content {
  margin-bottom: 10px;
  line-height: 1.6;
  white-space: pre-wrap;
  word-break: break-word;
}

.note-meta {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 0.85em;
  color: var(--hint-color);
}

.note-date {
  font-style: italic;
}

.note-actions {
  display: flex;
  gap: 8px;
}

/* 自定义滚动条 */
.notes-list::-webkit-scrollbar {
  width: 6px;
}

.notes-list::-webkit-scrollbar-track {
  background: var(--bg-color-diff);
}

.notes-list::-webkit-scrollbar-thumb {
  background-color: var(--primary-color);
  border-radius: 3px;
}
</style>